package cc.vv.btpartyjob.partymanager.activity

import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.WindowManager
import cc.vv.baselibrary.bean.base.BaseResponseObj
import cc.vv.baselibrary.http.BaseHttpRequest
import cc.vv.baselibrary.util.LKToastUtil
import cc.vv.baselibrary.util.VideoPlayerUtils
import cc.vv.baselibrary.view.BaseTopBarView
import cc.vv.baselibrary.view.imgselector.ImageSelector
import cc.vv.btpartyjob.jnimodule.api.JniModuleAPI
import cc.vv.btpartyjob.jnimodule.moudel.resp.FileUpResponseObj
import cc.vv.btpartyjob.jnimodule.server.ResourceChooseServer
import cc.vv.btpartyjob.partymanager.R
import cc.vv.btpartyjob.partymanager.api.PartyManagerAPI
import cc.vv.btpartyjob.partymanager.delegate.AddWorkQingKuangActivityDelegate
import cc.vv.btpartyjob.partymanager.delegate.ManagerBaseBinder
import cc.vv.btpartyjob.partymanager.moudel.bean.AddWorkingInfoObj
import cc.vv.btpartyjob.partymanager.moudel.resp.AddQianDaoResponseObj
import cc.vv.lkbasecomponent.http.lib.setting.Settings
import cc.vv.lklibrary.http.base.okhttpfactory.plugins.httpplugin.MediaTypeWrap
import cc.vv.mvp.activity.BaseActivityMVP
import cc.vv.mvp.binder.BaseDataBinder
import com.dawning.utiming.task.bean.FileUrlObj
import com.dawning.utiming.task.inter.SelectedOrDeleteFileInterface
import com.dawning.utiming.task.server.SubmitJobServer
import com.zxy.tiny.Tiny
import com.zxy.tiny.callback.FileWithBitmapCallback

/**
 * 添加工作情况
 * Created by Chen.qi on 2018/10/27.
 */
class AddWorkQingKuangActivity : BaseActivityMVP<AddWorkQingKuangActivityDelegate>()
        , SelectedOrDeleteFileInterface {

    /**
     * 固定占位数据
     */
    private val zwStrData = "zhaWeiShuJu"

    /**
     * 图片压缩操作
     */
    private var optionsImage: Tiny.FileCompressOptions? = null

    /**
     * 本地数据集合
     */
    private var locationList: ArrayList<FileUrlObj>? = null

    private var id: String? = null

    override fun initData() {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
        viewDelegate?.setTopBarTitle("添加")
        id = intent.getStringExtra("id")
        optionsImage = Tiny.FileCompressOptions()
        locationList = ArrayList()
        viewDelegate.setSelectedFileInterface(this)

        val obj = FileUrlObj(zwStrData, "")
        locationList!!.add(obj)
        viewDelegate.setSelectedFileObj(locationList)


    }

    override fun bindEvenListener() {
        viewDelegate?.setTitleBackBtnOnClick(object : BaseTopBarView.EventInterface {
            //返回
            override fun leftOnClick() {
                finish()
            }

            override fun leftCloseClick() {}
            override fun rightOnClick() {
            }


        })


        viewDelegate?.setOnClickListener(View.OnClickListener {


            val zhuTi = viewDelegate?.getZhuTi()
            if (TextUtils.isEmpty(zhuTi)) {
                LKToastUtil.showToastShort("请输入主题")
                return@OnClickListener
            }

            val content = viewDelegate?.getContent()
            if (TextUtils.isEmpty(content)) {
                LKToastUtil.showToastShort("请添加内容")
                return@OnClickListener
            }

            val list = ArrayList<String>()
            for (i in 0 until locationList!!.size) {
                if (!TextUtils.isEmpty(locationList!![i].serverUrl)) {
                    list.add(locationList!![i].serverUrl!!)
                }
            }

            val param = AddWorkingInfoObj()
            if (list.size > 0) {
                param.imgList = list
            }
            param.teamId = id
            param.content = content
            param.title = zhuTi
            BaseHttpRequest.postRequest(PartyManagerAPI.addWorkingInfo,
                    param, AddQianDaoResponseObj::class.java, true,
                    Settings(MediaTypeWrap.MEDIA_TYPE_RAW_JSON))


        }, R.id.rl_adwQK_submit)


    }


    override fun getDelegateClass(): Class<AddWorkQingKuangActivityDelegate> {
        return AddWorkQingKuangActivityDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {
        return ManagerBaseBinder()
    }


    override fun getData(obj: BaseResponseObj<*>?) {
        super.getData(obj)
        when (obj) {
            is FileUpResponseObj -> {
                //头像
                val path = obj.data.url
                uploadServerSuccessImage(path, 0)
            }

            is AddQianDaoResponseObj -> {
                LKToastUtil.showToastShort("添加成功")
                setResult(101)
                finish()
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (null == data || resultCode != BaseActivityMVP.RESULT_OK) {
            return
        }
        val imagePath: ArrayList<String>? = data.getStringArrayListExtra(ImageSelector.SELECTED_RESULT)
        if (null != imagePath && imagePath.size > 0) {
            for (i in 0 until imagePath.size) {
                val filePath = imagePath[i]
                compressPic(filePath, optionsImage, this)
            }
        }
    }


    /**
     * 压缩图片
     */
    private fun compressPic(filePath: String, optionsImage: Tiny.FileCompressOptions?, sInterface: SelectedOrDeleteFileInterface?) {
        Tiny.getInstance().source(filePath).asFile().withOptions(optionsImage)
                .compress(FileWithBitmapCallback { isSuccess, bitmap, outfile, throwable ->
                    if (isSuccess) {
                        fileUpload(outfile)
                    } else {
                        if (TextUtils.isEmpty(filePath)) {
                            return@FileWithBitmapCallback
                        }
                        fileUpload(filePath)
                    }
                })
    }


    private fun fileUpload(imgUrl: String) {
        val uploadFile = ResourceChooseServer.uploadFile(imgUrl)
        if (null == uploadFile) {
            LKToastUtil.showToastShort("头像上传失败")
            return
        }
        val headPath = JniModuleAPI.uploadHeadHttp
        BaseHttpRequest.postFileRequest(headPath, uploadFile, FileUpResponseObj::class.java, true)
    }


    override fun lookLargerImage(position: Int, type: Int) {
        val list = ArrayList<String>()
        for (i in 0 until locationList!!.size) {
            if (zwStrData != locationList!![i].localPath) {
                list.add(locationList!![i].localPath!!)
            } else {
                locationList!!.remove(locationList!![i])
            }
        }
        SubmitJobServer.largePic(this, list, position)
    }

    override fun playingVideo(videoPath: String, type: Int) {
        Log.e("lk_chen", "result看啊看地址-----==" + videoPath);
        VideoPlayerUtils.getInstance().playVideo(this, videoPath)

    }

    override fun deleteFile(position: Int, type: Int) {
        val strRemove = locationList!![position]
        SubmitJobServer.delKey = strRemove.serverUrl
        locationList!!.remove(strRemove)
        val fileNormal = FileUrlObj(zwStrData, "")
        locationList!!.remove(fileNormal)
        locationList!!.add(fileNormal)
        viewDelegate?.setSelectedFileObj(locationList)
    }

    override fun continueSelectedFile(type: Int) {
        val fileNormal = FileUrlObj(zwStrData, "")
        locationList!!.remove(fileNormal)
        SubmitJobServer.openPic(this, 6 - locationList!!.size)
        if (locationList!!.size < 6) {
            locationList!!.add(fileNormal)
        }

    }

    override fun uploadServerSuccessImage(filePath: String, type: Int) {
        val fileObj = FileUrlObj(filePath, filePath)
        locationList!!.add(fileObj)

        val fileNormal = FileUrlObj(zwStrData, "")
        if (locationList!!.size <= 6) {
            locationList!!.remove(fileNormal)
            locationList!!.add(fileNormal)
        } else {
            locationList!!.remove(fileNormal)
        }
        viewDelegate?.setSelectedFileObj(locationList)

    }

    override fun uploadServerFailPic(filePath: String, type: Int) {
    }


}